package com.example.springboot.service.impl;;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.entity.Comment;
import com.example.springboot.mapper.CommentMapper;
import com.example.springboot.service.ICommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.*;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService{

    @Autowired
    private CommentMapper commentMapper;

    @Override
    public boolean save(Comment entity) {
        // 处理rootId：子评论继承根评论ID
        if (entity.getPid() != 0) {
            Comment parent = getById(entity.getPid()); // MyBatis-Plus自带方法
            entity.setRootId(parent.getRootId() == 0 ? parent.getId() : parent.getRootId());
        } else {
            entity.setRootId(0); // 顶级评论rootId=0
        }
        entity.setTime(DateUtil.now()); // 设置当前时间
        return super.save(entity);
    }

    @Override
    public boolean updateById(Comment entity) {
        return super.updateById(entity);
    }

    @Override
    public boolean removeById(Comment entity) {
        return super.removeById(entity);
    }

    @Override
    public boolean removeBatchByIds(Collection<?> list) {
        return super.removeBatchByIds(list);
    }

    @Override
    public List<Comment> list() {
        return super.list();
    }

    @Override
    public Comment getById(Serializable id) {
        return super.getById(id);
    }

    @Override
    public <E extends IPage<Comment>> E page(E page, Wrapper<Comment> queryWrapper) {
        return super.page(page, queryWrapper);
    }

    @Override
    public List<Comment> getCommentTree(Integer fid) {
        // 查该图书下所有评论（含用户信息）
        List<Comment> allComments = commentMapper.selectByFidWithUser(fid);
        if (allComments.isEmpty()) return new ArrayList<>();

        // 用Map存：评论ID → 评论对象（快速找父评论）
        Map<Integer, Comment> commentMap = new HashMap<>();
        for (Comment comment : allComments) {
            comment.setChildren(new ArrayList<>()); // 初始化子评论列表
            commentMap.put(comment.getId(), comment);
        }

        // 组装树形结构
        List<Comment> rootComments = new ArrayList<>();
        for (Comment comment : allComments) {
            if (comment.getPid() == 0) {
                // 顶级评论：直接加入根列表
                rootComments.add(comment);
            } else {
                // 子评论：添加到父评论的children中
                Comment parent = commentMap.get(comment.getPid());
                if (parent != null) {
                    parent.getChildren().add(comment);
                }
            }
        }
        return rootComments;
    }
}
